package cn.information.view.extend;

import cn.information.bean.Purchase;
import cn.information.dao.PurchaseDao;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.util.List;
import java.util.Vector;

public class PurchaseQueryResultUI extends JFrame {
    private JScrollPane jScrollPane = new JScrollPane();
    private AbstractTableModel tableModel;
    private Vector<Vector> vector = new Vector<>();
    private PurchaseDao dao = new PurchaseDao();


    public PurchaseQueryResultUI(String purchaseName) {
        setTitle("顾客姓名查询结果 - " + purchaseName);
        setBounds(300, 200, 800, 400);
        setLayout(new BorderLayout());

        JPanel panelUp = new JPanel();
        JPanel panelDown = new JPanel();

        panelUp.add(jScrollPane);
        createTable(purchaseName);

        add(panelUp, BorderLayout.CENTER);
        add(panelDown, BorderLayout.SOUTH);

        JButton btnBack = new JButton("返回");
        btnBack.addActionListener(e -> {
            new PurchaseQueryUI().setVisible(true);
            dispose();
        });
        panelDown.add(btnBack);

        JButton btnExit = new JButton("退出");
        btnExit.addActionListener(e -> dispose());
        panelDown.add(btnExit);

        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }
    private void createTable(String purchaseName) {
        String[] columnNames = {"商品ID", "顾客ID", "顾客姓名", "日期", "商品名称", "商品价格", "商品数量", "顾客电话"};
        JTable table = new JTable();
        jScrollPane.setViewportView(table);

        List<Purchase> list= dao.findByName(purchaseName);
        for (Purchase purchase : list) {
            Vector<Object> v = new Vector<>();
            v.add(purchase.getSpid());
            v.add(purchase.getGkid());
            v.add(purchase.getGkname());
            v.add(purchase.getDate());
            v.add(purchase.getSpname());
            v.add(purchase.getSpprice());
            v.add(purchase.getSpnumber());
            v.add(purchase.getGkphone());
            vector.add(v);
        }
        tableModel = new AbstractTableModel() {
            @Override
            public int getRowCount() {
                return vector.size();
            }

            @Override
            public String getColumnName(int column) {
                return columnNames[column];
            }

            @Override
            public int getColumnCount() {
                return columnNames.length;
            }

            @Override
            public Object getValueAt(int rowIndex, int columnIndex) {
                if (rowIndex < vector.size()) {
                    Vector v = vector.get(rowIndex);
                    return v.get(columnIndex);
                } else {
                    return null;
                }
            }
        };
        table.setModel(tableModel);

    }

}


